<template>
  <div class="view-fill">
    <div
      v-if="
        !modifyInfo.visible &&
        !consumeDetailInfo.visible &&
        !receivingDetailInfo.visible &&
        !returnDetailInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="发票单详情"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canReject" @click="reject">驳回</el-button>
          <el-button v-if="canRevoke" @click="revoke">撤回</el-button>
          <el-button v-if="canRatify" @click="ratify">审核</el-button>
          <el-button v-if="canCancel" @click="cancel">作废</el-button>
          <el-button v-if="canExport" @click="exportDetailExcel"
            >导出excel</el-button
          >
          <!-- <el-button
            v-if="canPrint"
            @click="print"
            >打印</el-button
          > -->
          <!--  <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint> -->

          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information
              :info="infoList"
              :labelWidth="infoList.labelWidth"
            >
              <template v-slot:basic-filePathList>
                <EleGallery
                  v-if="infoList.data.filePathList"
                  :lazy="true"
                  :size="150"
                  :source="infoList.data.filePathList"
                  title="附件"
                />
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('detailInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :api="tableInfo.api"
                :summaryFieldList="tableInfo.summaryFieldList"
                :checkBox="false"
                :tab-index="true"
                v-model:query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :mergeData="tableInfo.mergeData"
                :mergeFiled="tableInfo.mergeFiled"
                :isDynamic="true"
              >
                <template v-slot:col-orderDescribeList="scope">
                  <div
                    v-if="
                      scope.row.orderDescribeList &&
                      scope.row.orderDescribeList.length
                    "
                  >
                    <div
                      v-for="(item, index) in scope.row.orderDescribeList"
                      :key="index"
                    >
                      <span>
                        {{
                          item.orderNo +
                          '-' +
                          item.settlementPrice +
                          '(元)-' +
                          item.calcQty
                        }}
                      </span>
                    </div>
                  </div>
                  <span v-else>-</span>
                </template>
              </PageTable>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <individualDetails
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :info="individualInfo.info"
      v-model:query="individualInfo.query"
      @callback="_individualDetails"
    />
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <ReceivingDetail
      v-if="receivingDetailInfo.visible"
      v-model:visible="receivingDetailInfo.visible"
      :id="receivingDetailInfo.id"
      :title="receivingDetailInfo.title"
      @returnModify="returnModify"
    />
    <ConsumeDetail
      v-if="consumeDetailInfo.visible"
      v-model:visible="consumeDetailInfo.visible"
      :id="consumeDetailInfo.id"
      :title="consumeDetailInfo.title"
      @returnModify="returnModify"
    />
    <ReturnDetail
      v-if="returnDetailInfo.visible"
      v-model:visible="returnDetailInfo.visible"
      :purchReturnId="returnDetailInfo.id"
      :title="returnDetailInfo.title"
      @returnModify="returnModify"
    />
  </div>
</template>

<script setup name="receiptOrderDetail">
import EleGallery from '@/components/UploadImgNew/eleGallery'
import ReceivingDetail from '@/views/stock/receiving/detail'
import ConsumeDetail from '@/views/stock/consumeOrder/detail'
import ReturnDetail from '@/views/purch/return/detail'
import { getCustomizeSetting } from '@/api/customize'
import individualDetails from './individualDetails'
import Modify from './modify'
import { fatchTemplateByCode } from '@/api/base'
import {
  submitReceiptOrder,
  revokeReceiptOrder,
  rejectReceiptOrder,
  ratifyReceiptOrder,
  cancelReceiptOrder,
  getReceiptOrderDetailCustomizeListAll,
  getReceiptOrderById,
  excelReceiptOrderDetail,
  printReceiptOrderDetail,
} from '@/api/receipt.js'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

import { orderAffairAll } from '@/api/affair'
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'id'])

const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
const infoList = ref({
  data: {},
  fieldList: [
    {
      label: '发票号',
      value: 'receiptNumber',
      type: 'text',
    },
    { label: '发货单号', value: 'deliverNo', type: 'text' },
    { label: '平台发票号', value: 'platformNumber', type: 'text' },
    { label: '单据来源', value: 'orderSourceValue', type: 'text' },
    {
      label: '发票类型',
      value: 'receiptTypeValue',
      type: 'text',
    },
    { label: '供应商', value: 'supplierName', type: 'text' },
    {
      label: '开票日期',
      value: 'receiptDate',
      type: 'text',
    },
    {
      label: '开票金额',
      value: 'receiptAmount',
      type: 'text',
    },
    {
      label: '出入库金额',
      value: 'exportStoreAmount',
      type: 'text',
    },
    {
      label: '结算方式',
      value: 'settleTypeValue',
      type: 'text',
    },
    {
      label: '发票张数',
      value: 'receiptCount',
      type: 'text',
    },
    {
      label: '状态',
      value: 'statusValue',
      type: 'text',
    },
    {
      label: '附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
  ],
  labelWidth: '130px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },
})
// 表格相关
const tableInfo = ref({
  api: null,
  refresh: 1,
  initCurpage: 1,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'receiveQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'refuseQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  selections: [],
  data: [],
  mergeData: {},
  mergeFiled: ['sumAmount'],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '明细详情',
        event: individual,
        show: true,
      },
    ],
  },
})
const affairTableInfo = ref({
  query: {
    orderType: 72,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const individualInfo = ref({
  visible: false,
  query: {
    orderDetailId: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: null,
    },
  },
  info: {
    commonName: '',
    batchNumber: '',
    extDetails: [],
  },
})
const receivingDetailInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const consumeDetailInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const returnDetailInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('receiptOrder:update') &&
    infoList.value.data.status === 1 &&
    infoList.value.data.orderSource === 1
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('receiptOrder:submit') &&
    infoList.value.data.status === 1 &&
    infoList.value.data.orderSource === 1
  )
})
const canReject = computed(() => {
  return (
    proxy.$permission('receiptOrder:reject') && infoList.value.data.status === 2
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('receiptOrder:revoke') &&
    infoList.value.data.status === 2 &&
    infoList.value.data.orderSource === 1
  )
})
const canRatify = computed(() => {
  return (
    proxy.$permission('receiptOrder:ratify') && infoList.value.data.status === 2
  )
})
const canCancel = computed(() => {
  return (
    proxy.$permission('receiptOrder:invalid') &&
    infoList.value.data.status === 5 &&
    infoList.value.data.orderSource === 1
  )
})
const canExport = computed(() => {
  return proxy.$permission('receiptOrder:exportDetail')
})
const canPrint = computed(() => {
  return proxy.$permission('receiptOrder:printDetail')
})
let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  baseProductTypeValue: {
    label: '产品类型',
    value: 'baseProductTypeValue',
    asValue: 'baseProductType',
    componentType: 'select-model',
    code: 'new_product_type',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
function returnModify() {
  getMain()
  getList()
}
function returnBack() {
  proxy.$emit('returnBack', false)
}
//更新
function update() {
  modifyInfo.value.title = '修改发票单'
  modifyInfo.value.orderId = infoList.value.data.id
  modifyInfo.value.visible = true
}
//提交
function submit() {
  const ids = [infoList.value.data.id]
  submitReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
//驳回
function reject() {
  const ids = [infoList.value.data.id]
  rejectReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
//审核
function ratify() {
  const ids = [infoList.value.data.id]
  ratifyReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
//撤回
function revoke() {
  const ids = [infoList.value.data.id]
  revokeReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
//作废
function cancel() {
  const ids = [infoList.value.data.id]
  cancelReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
function exportDetailExcel() {
  excelReceiptOrderDetail(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'receiptOrderDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.value.data.id,
            orderId: infoList.value.data.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.value.data.id,
      orderId: infoList.value.data.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      tempCode: 'receiptOrderDetail',
      orderId: props.id,
      orderType: 72,
    })
  } catch (error) {}
}
function individual(row) {
  individualInfo.value.visible = true
  individualInfo.value.info.commonName = row.commonName
  individualInfo.value.info.batchNumber = row.batchNumber
  individualInfo.value.query.orderDetailId.value = row.id
}
function _individualDetails(row) {
  if (row.businessOrderType === 25) {
    //跳转到消耗
    consumeDetailInfo.value.id = row.businessOrderId
    consumeDetailInfo.value.visible = true
    consumeDetailInfo.value.title = '消耗明细'
  } else if (row.businessOrderType === 15) {
    //跳转入库
    receivingDetailInfo.value.id = row.businessOrderId
    receivingDetailInfo.value.visible = true
    receivingDetailInfo.value.title = '收货单明细'
  } else if (row.businessOrderType === 1) {
    //采购退货
    returnDetailInfo.value.id = row.businessOrderId
    returnDetailInfo.value.visible = true
    returnDetailInfo.value.title = '采购退货明细'
  } else {
    proxy.$message.warning('业务类型未找到,请联系管理员')
  }
}
function getList() {
  getReceiptOrderDetailCustomizeListAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
      tableInfo.value.data.forEach((item) => {
        let data = []
        if (item.orderDescribe) {
          let orderDescribeList = item.orderDescribe.split(',')
          orderDescribeList.forEach((el) => {
            let arr = el.split('-')
            let obj = {
              orderNo: arr[0],
              settlementPrice: arr[1].split('(元')[0],
              calcQty: arr[2] ? arr[2] : '-' + arr[3],
            }
            data.push(obj)
          })
        }
        item['orderDescribeList'] = data
      })
    }
  })
}
function getMain() {
  getReceiptOrderById(props.id).then((res) => {
    if (res && res.success) {
      infoList.value.data = res.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'receiptOrderDetail-com.slip.spd.entity.vo.receipt.ReceiptOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      getMain()
      getList()
    }
  })
}
</script>
<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
:deep(.el-dialog__body) {
  height: 355px;
  display: flex;
  flex-direction: column;
}
</style>
